package cn.com.anysdk.starter.config.redis;

import cn.com.anysdk.redis.api.IRedisService;
import cn.com.anysdk.redis.config.LocalRedisConfig;
import cn.com.anysdk.redis.config.RedisConfigProperties;
import cn.com.anysdk.redis.event.RedisEventManager;
import cn.com.anysdk.redis.impl.LocalRedisServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 本地Redis自动配置类
 * 当配置anysdk.redis.local.enabled=true时启用
 */
@Configuration
@EnableConfigurationProperties(LocalRedisProperties.class)
@ConditionalOnProperty(prefix = "anysdk.redis.local", name = "enabled", havingValue = "true")
public class LocalRedisAutoConfiguration {
    
    private static final Logger log = LoggerFactory.getLogger(LocalRedisAutoConfiguration.class);
    
    /**
     * 创建本地Redis配置
     */
    @Bean
    public LocalRedisConfig localRedisConfig(LocalRedisProperties properties) {
        log.info("创建本地Redis配置，主机: {}:{}, 数据库: {}", properties.getHost(), properties.getPort(), properties.getDatabase());
        
        LocalRedisConfig config = new LocalRedisConfig();
        config.setHost(properties.getHost());
        config.setPort(properties.getPort());
        config.setPassword(properties.getPassword());
        config.setDatabase(properties.getDatabase());
        
        return config;
    }
    
    /**
     * 创建Redis配置属性
     */
    @Bean
    public RedisConfigProperties localRedisConfigProperties(LocalRedisConfig localConfig) {
        RedisConfigProperties config = new RedisConfigProperties();
        config.setEnvironment("local");
        
        // 设置本地配置
        RedisConfigProperties.LocalConfig localConfigProps = new RedisConfigProperties.LocalConfig();
        localConfigProps.setHost(localConfig.getHost());
        localConfigProps.setPort(localConfig.getPort());
        localConfigProps.setPassword(localConfig.getPassword());
        localConfigProps.setDatabase(localConfig.getDatabase());
        
        config.setLocal(localConfigProps);
        
        return config;
    }

    @Bean
    public RedisEventManager redisEventManager() {
        log.info("创建Redis事件管理器实例");
        return new RedisEventManager();
    }
    
    /**
     * 创建本地Redis服务
     */
    @Bean(name = "localRedisService")
    public IRedisService localRedisService(RedisConfigProperties config, RedisEventManager eventManager) {
        log.info("创建本地Redis服务实例");
        return new LocalRedisServiceImpl(config, eventManager);
    }
}